const express = require('express');
const router = express.Router();
const anchorMod = require('../../db/cloudControl/anchorMod');
const userMod = require('../../db/cloudControl/userMod');

// 批量上传主播数据
router.post('/batchUpload', async (req, res) => {
    try {
        const { userName, anchorList } = req.body;
        console.log(userName,anchorList)

        // 验证必填参数
        if (!userName) {
            return res.json({
                code: -1,
                msg: '用户名不能为空'
            });
        }

        if (!Array.isArray(anchorList) || anchorList.length === 0) {
            return res.json({
                code: -1,
                msg: '主播数据列表不能为空'
            });
        }

        // 查询用户
        const user = await userMod.findOne({ userName: userName });
        if (!user) {
            return res.json({
                code: -1,
                msg: '用户不存在'
            });
        }

        // 批量处理数据
        const bulkOps = anchorList.map(anchor => {
            const baseData = {
                ...anchor,
                admin: user._id
            };

            // 如果有displayId，使用upsert更新，否则插入新数据
            if (anchor.displayId) {
                return {
                    updateOne: {
                        filter: { displayId: anchor.displayId },
                        update: { $set: baseData },
                        upsert: true
                    }
                };
            } else {
                return {
                    insertOne: {
                        document: baseData
                    }
                };
            }
        });

        const result = await anchorMod.bulkWrite(bulkOps);

        res.json({
            code: 0,
            data: {
                matched: result.matchedCount,
                modified: result.modifiedCount,
                inserted: result.insertedCount
            },
            msg: '批量上传成功'
        });
    } catch (error) {
        res.json({
            code: -1,
            msg: error.message
        });
    }
});

module.exports = router;